package com.zhiyou.app.config.ordertaskhandler;

import com.zhiyou.app.common.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

/**
 * orderTask处理器帮助类
 *
 * @author zhangqiang
 */
@Slf4j
@Component
public class OrderTaskHandlerHelper implements ApplicationContextAware {
    private final Map<String, Class<? extends BaseOrderTaskHandler<? extends BaseOrderTaskHandler<?>>>> handlerClassMap = new HashMap<>();
    private ApplicationContext applicationContext;

    @SuppressWarnings("unchecked")
    @PostConstruct
    public void init() {
        // 通过ApplicationContext动态获取所有BaseOrderTaskHandler的实现类
        Map<String, BaseOrderTaskHandler> beansOfType = applicationContext.getBeansOfType(BaseOrderTaskHandler.class);
        for (BaseOrderTaskHandler<? extends BaseOrderTaskHandler<?>> handler : beansOfType.values()) {
            // 通过getTaskType方法获取类型，并关联到具体的Class
            handlerClassMap.put(handler.getTaskType(), (Class<? extends BaseOrderTaskHandler<? extends BaseOrderTaskHandler<?>>>) handler.getClass());
        }
    }

    public BaseOrderTaskHandler<?> getOrderTaskHandler(String taskType) {
        return getOrderTaskHandler(taskType, null);
    }

    public BaseOrderTaskHandler<? extends BaseOrderTaskHandler<?>> getOrderTaskHandler(String taskType, String param) {
        Class<? extends BaseOrderTaskHandler<? extends BaseOrderTaskHandler<?>>> handlerClass = handlerClassMap.get(taskType);
        if (handlerClass != null) {
            try {
                // 每次都从Spring容器获取新的实例，确保线程安全
                BaseOrderTaskHandler<? extends BaseOrderTaskHandler<?>> bean = applicationContext.getBean(handlerClass);
                if (param != null) {
                    bean.postInitParam(param);
                }
                return bean;
            } catch (BeansException e) {
                log.error("无法创建任务处理器实例: " + taskType, e);
                throw new BizException("无法创建任务处理器实例: " + taskType);
            }
        }
        return null;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}